﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MatchCore;
using Net.Messgae;

public class UIPlayerController : MonoBehaviour,IPlayerEventer
{
    public UnityEngine.UI.Slider bloodController;

    public GameObject shootPointer;

    public GameObject bulletPanel;

    private Player _player;

    private float _speed = 1.0f;


    public static void GetPlayerInfoByIndex(uint index,ref MatchCore.Vector2 pos,
        ref MatchCore.Vector2 shootOffsetPos,ref int shootDir)
    {
        pos.y = Config.SCENE_SIZE.y / 2;
        shootOffsetPos.y = Config.PLAYER_SIZE.y / 2;

        if(1 == index)
        {
            pos.x = Config.PLAYER_SIZE.x / 2;
            shootOffsetPos.x = Config.PLAYER_SIZE.x / 2;
            shootDir = 1;
        }
        else
        {
            pos.x = Config.SCENE_SIZE.x - Config.PLAYER_SIZE.x / 2;
            shootOffsetPos.x = -Config.PLAYER_SIZE.x / 2;
            shootDir = -1;
        }
    }

    public Player CreatePlayer(GamePlayerInfo playerInfo)
    {
        MatchCore.Vector2 pos = new MatchCore.Vector2();
        MatchCore.Vector2 shootOffsetPos = new MatchCore.Vector2();
        int shootDir = 0;

        GetPlayerInfoByIndex(playerInfo.Index,ref pos,ref shootOffsetPos,ref shootDir);

        _player = new Player(playerInfo.Index,pos,shootOffsetPos,Config.PLAYER_MOVE_SPEED,
            shootDir,Config.PLAYER_BLOOD_NUM);

        _player.SetEventer(this);

        _speed = Config.GAME_PER_SEC_FRAME_NUM * _player.GetSpeed() 
            * UITransformHelper.GetUISceneSize().y / Config.SCENE_SIZE.y;

        return _player;
    }

    public void OnShoot(Player player, Bullet bullet)
    {
        UnityEngine.Object prefabObj = Resources.Load("prefabs/Bullet");
        GameObject go = (GameObject)Instantiate(prefabObj);
        go.transform.SetParent(shootPointer.transform);
        // var rectTran = (RectTransform)go.transform;
        // rectTran.offsetMin = new UnityEngine.Vector2(0,0);
        // rectTran.offsetMax = new UnityEngine.Vector2(0,0);

        var uiBullet = go.GetComponent<UIBulletController>();
        uiBullet.SetBullet(bullet);
    }

    public void OnBeShoot(Player player, int subBlood)
    {
        bloodController.value = player.GetBlood() / (1.0f * Config.PLAYER_BLOOD_NUM);
    }

    void Update()
    {
        if(_player != null)
        {
            UnityEngine.Vector3 pos = UITransformHelper.Match2UIPosition(_player.GetPosition());
            UnityEngine.Vector3 sub = pos - transform.position;
            if(Math.Abs(sub.x) >= 1 || Math.Abs(sub.y) >= 1)
            {
                // transform.position = transform.position 
                //     + new UnityEngine.Vector3(sub.x * Time.deltaTime,sub.y * Time.deltaTime,0);
                transform.position = pos;
            }
        }
    }
}
